<template>
  <div class="form-container">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" class="form-class">
      <!-- 手机号码输入框 -->
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机号码" clearable>
          <template #append>
            <el-button
              class="send-code-btn"
              :disabled="isSending || countdown > 0"
              @click="sendCode"
            >
              {{ countdown > 0 ? `${countdown}秒后重试` : "获取验证码" }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>

      <!-- 验证码输入框 -->
      <el-form-item label="验证码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入验证码" class="code-input"></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup>
import CommonAPI from "@/api/system/common";
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";

const formRef = ref(null); // 表单引用
const formData = reactive({
  phone: "",
  code: "",
});

const rules = reactive({
  phone: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入有效的手机号码", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { len: 6, message: "验证码长度为6位", trigger: "blur" },
  ],
});

const isSending = ref(false); // 是否正在发送验证码
const countdown = ref(0); // 验证码倒计时

// 发送验证码
const sendCode = async () => {
  formRef.value.validateField("phone", async (valid) => {
    if (valid) {
      try {
        isSending.value = true;
        countdown.value = 60; // 设置倒计时为60秒
        const data = await CommonAPI.captchaSmse({ phone: formData.phone });
        console.log(data);
        ElMessage.success("验证码已发送，请注意查收");
      } catch (error) {
        ElMessage.error("验证码发送失败");
      } finally {
        const interval = setInterval(() => {
          countdown.value--;
          if (countdown.value <= 0) {
            clearInterval(interval);
            isSending.value = false;
          }
        }, 1000);
      }
    } else {
      ElMessage.error("请输入有效的手机号码");
    }
  });
};
const getFormData = () => {
  return formData;
};
defineExpose({
  formRef,
  getFormData,
});
</script>
<style scoped>
/* .form-container {
  max-width: 400px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
} */
</style>
